import React, { useState, useEffect } from 'react';
import { Table, Button, message } from 'antd';
import { getBorrowList, updateBorrowStatus, permitUpdate } from '../../../services/api';

const ReturnList = () => {
  const [loading, setLoading] = useState(false);
  const [borrowList, setBorrowList] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 从sessionStorage获取用户信息
  const userInfo = JSON.parse(sessionStorage.getItem('user') || '{}');
  const isAdmin = userInfo.admin === 'yes';

  const handleReturn = async (record) => {
    try {
      setLoading(true);
      if (isAdmin) {
        // 管理员直接归还
        // 1. 更新资产数量
        const updateAssetResponse = await permitUpdate(record.assetId, {
          assetNum: record.borrowNum,
          assetStatus: 'return' // 操作类型：归还
        });

        if (updateAssetResponse.code !== 200) {
          message.error('更新资产数量失败, '+ updateAssetResponse.message);
          return;
        }

        // 2. 更新借用状态
        const updateStatusResponse = await updateBorrowStatus(record.borrowId, {
          borrowStatus: '已归还'
        });

        if (updateStatusResponse.code === 200) {
          message.success('资产归还成功');
        } else {
          message.error('更新借用状态失败');
        }
      } else {
        // 普通用户提交归还申请
        const updateStatusResponse = await updateBorrowStatus(record.borrowId, {
          borrowStatus: '待归还'
        });

        if (updateStatusResponse.code === 200) {
          message.success('归还申请已提交，请等待管理员审批');
        } else {
          message.error('提交归还申请失败');
        }
      }
      fetchBorrowList(); // 刷新列表
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '借用ID',
      dataIndex: 'borrowId',
      key: 'borrowId',
    },
    {
      title: '借用人',
      dataIndex: 'uname',
      key: 'uname',
    },
    {
      title: '所属部门',
      dataIndex: 'depName',
      key: 'depName',
    },
    {
      title: '资产名称',
      dataIndex: 'assetName',
      key: 'assetName',
    },
    {
      title: '借用状态',
      dataIndex: 'borrowStatus',
      key: 'borrowStatus',
    },
    {
      title: '借用数量',
      dataIndex: 'borrowNum',
      key: 'borrowNum',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        // 只有状态为"已借出"的记录才显示按钮
        if (record.borrowStatus === '已借出') {
          return (
            <Button 
              type="primary" 
              onClick={() => handleReturn(record)}
            >
              {isAdmin ? '直接归还' : '申请归还'}
            </Button>
          );
        }
        return null;
      },
    },
  ];

  const fetchBorrowList = async () => {
    try {
      setLoading(true);
      const response = await getBorrowList();
      if (response.code === 200 && Array.isArray(response.data)) {
        // 过滤出未归还的记录（状态为"已借出"）
        let filteredList = response.data.filter(item => item.borrowStatus === '已借出');
        
        // 如果不是管理员，只显示自己的记录
        if (!isAdmin) {
          filteredList = filteredList.filter(item => item.uid === userInfo.uid);
        }
        
        console.log('过滤后的列表:', filteredList); // 添加调试日志
        
        setBorrowList(filteredList);
        setPagination(prev => ({
          ...prev,
          total: filteredList.length
        }));
      } else {
        message.error(response.message || '获取借用记录失败');
      }
    } catch (error) {
      console.error('获取借用记录失败:', error);
      message.error('获取借用记录失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchBorrowList();
  }, []);

  const handleTableChange = (newPagination) => {
    setPagination(newPagination);
  };

  return (
    <div style={{ padding: '24px' }}>
      <h2>资产归还</h2>
      <div style={{ marginBottom: '16px' }}>
        {isAdmin ? '显示所有未归还的资产' : '显示您的未归还资产'}
      </div>
      <Table
        columns={columns}
        dataSource={borrowList}
        rowKey="borrowId"
        pagination={pagination}
        onChange={handleTableChange}
        loading={loading}
      />
    </div>
  );
};

export default ReturnList; 